# coding=utf-8
import socket
import struct
import multiprocessing
import time

#import GPS_SEND
import USART
# 定义服务器的IP和端口
host = '192.168.178.250'
port = 6666

#定义一个数组进行保存变量
lat_long = [0,0,0,0]

# 定义变量来存储数据，初始值全部为0.0，为0.0时为无效值，对于没使用到的值应全部置0.0
get_check1 = 0.0       # 校验位1（888.0有效）
get_speed = 0.0       # 速度
get_mode = 0.0        # 飞行模式/任务：1.0表示...2.0表示...
get_doit = 0.0        # 执行确认位(1.0表示有效，0.0表示无效)
get_longitude = [0.0,0.0,0.0,0.0]   # 新建一个列表来存储经度,longitude[0]和latitude[0]为一对
get_latitude =  [0.0,0.0,0.0,0.0]   # 列表存储纬度
get_altitude =  [0.0,0.0,0.0,0.0]   # 列表存储海拔（高度）
get_check2 = 0.0       # 校验位（666.0有效）

send_check1 = 888.0
send_speed = 0.0
send_mode = 0.0        # 飞行模式/任务：1.0表示...2.0表示...
send_doit = 1.0        # 执行确认位(1.0表示有效，0.0表示无效)
send_longitude = [0.0,0.0,0.0,0.0]   # 新建一个列表来存储经度,longitude[0]和latitude[0]为一对
send_latitude =  [0.0,0.0,0.0,0.0]   # 列表存储纬度
send_altitude =  [0.0,0.0,0.0,0.0]   # 列表存储海拔（高度）
send_check2 = 666.0

# 创建 TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
data_queue = multiprocessing.Queue()


def start_server():
    global get_longitude
    global get_latitude
    global get_altitude
    global lat_long
    # 绑定 IP 和端口
    server_socket.bind((host, port))

    # 开始监听连接
    server_socket.listen(5)  # 最多允许5个待连接的客户端
    print(f"服务器启动，监听 {host}:{port}...")

    try:
        while True:
            # 接受客户端连接
            client_socket, addr = server_socket.accept()
            print(f"连接来自 {addr}")

            while True:
                # 接收 16 个 double 的数据，总大小为 128 字节
                data = client_socket.recv(128)  # 每个 double 是 8 字节
                if not data:
                    print(f"客户端 {addr} 已断开连接")
                    break  # 退出内层循环，等待下一个客户端

                # 解包接收到的数据
                try:
                    unpacked_data = struct.unpack('>17d', data)
                    get_check1, get_speed, get_mode, get_doit, \
                    get_longitude[0], get_latitude[0], get_altitude[0], \
                    get_longitude[1], get_latitude[1], get_altitude[1], \
                    get_longitude[2], get_latitude[2], get_altitude[2], \
                    get_longitude[3], get_latitude[3], get_altitude[3],get_check2 = unpacked_data

                    print(f"收到来自 {addr} 的数据:")
                    print(f"  经度: {get_longitude[0]}")
                    print(type(get_longitude[0]))
                    print(f"  纬度: {get_altitude[0]}")
                except struct.error as e:
                    print(f"解包数据时发生错误: {e}")

                if get_check1 == 888.0 and get_check2 == 666.0:
                    send_check1 = 888.0
                    send_speed = 0.0
                    send_mode = 0.0  # 飞行模式/任务：1.0表示...2.0表示...
                    send_doit = 1.0  # 执行确认位(1.0表示有效，0.0表示无效)
                    send_longitude = [0.0, 0.0, 0.0, 0.0]  # 新建一个列表来存储经度,longitude[0]和latitude[0]为一对
                    send_latitude = [0.0, 0.0, 0.0, 0.0]  # 列表存储纬度
                    send_altitude = [0.0, 0.0, 0.0, 0.0]  # 列表存储海拔（高度）
                    send_check2 = 666.0
                    # 获取到经纬度数据就需要，发送确认信息 send_doit=1.0
                    datas_to_send = [send_check1, send_speed,send_mode,send_doit,\
                                send_longitude[0], send_latitude[0],send_altitude[0],\
                                send_longitude[1], send_latitude[1],send_altitude[1],\
                                send_longitude[2], send_latitude[2],send_altitude[2],\
                                send_longitude[3], send_latitude[3],send_altitude[3],send_check2]
                    try:
                        # 使用 struct 打包数据，16个 double 类型
                        packed_data = struct.pack('>17d', *datas_to_send)
                        # 发送打包的数据到服务器
                        client_socket.sendall(packed_data)
                        print(f"Sent data: {datas_to_send}")
                        send_doit = 0.0  # 确认位清零
                    except BlockingIOError:
                        print("发送数据时阻塞，请稍后再试。")
                    except Exception as e:
                        print(f"发送数据时出错: {e}")

                    #获取GPS的经纬度数据通过float_to_int处理
                    # 并保存到两个数组lat,lon,然后进行合并一个数组进行返回出去
                    lat = GPS_SEND.float_to_int(get_latitude[0],lat_long)
                    lon = GPS_SEND.float_to_int(get_longitude[0],lat_long)
                    lat_and_lon = lat + lon
                return lat_and_lon

            # 关闭当前客户端连接
            client_socket.close()
            print(f"关闭与 {addr} 的连接，准备接收下一个连接...")

    except KeyboardInterrupt:
        print("\n服务器正在关闭...")
    finally:
        server_socket.close()
        print("服务器已关闭。")

if __name__ == "__main__":
    #打开小车的串口
    recieve_data=0
    flag=0
    sender = USART.SerialSender("/dev/ttyS4", 115200)
    print("/dev/ttyS4;115200")
    lat_air1=[0xFF,0x13,0x01,0,0,0,0,0xAA]
    lon_air1=[0xFF,0x13,0x02,0,0,0,0,0xAA]
    xaryy= [0xFF,0x01,0,0,0xAA]
    lat_car2=[0xFF,0x13,0x01,0,0,0,0,0xAA]
    lon_car2=[0xFF,0x13,0x02,0,0,0,0,0xAA]

    #获取飞机的经纬度lat_and_lon_air=[12,23,44,33,180,33,22,11]
    #飞机的经纬度只获取一次，，后续不获取了
    #lat_and_lon_air = start_server()
    lat_and_lon_air = [21,67,63,89,110,92,39,56]
    
    #lat_and_lon_air = [21,67,61,85,110,92,34,81]
    print(lat_and_lon_air)
    for i in range(4) :
        #[0xFF,0x06,0x01,12,23,44,33,0xAA]
        lat_air1[i+3] = int(lat_and_lon_air[i])
        #[0xFF,0x06,0x02,180,33,22,11,0xAA]
        lon_air1[i+3] = int(lat_and_lon_air[i+4])
    if flag == 0:
        #发送一次目标经纬度
        sender.air_GPS(lat_air1)
        time.sleep(2)
        sender.air_GPS(lon_air1)
        time.sleep(0)
        flag =1

    while True:
        #接收底层发上来的数据，判断需不需要在获取小车的坐标值
        recieve_data = sender.receive_integer()
        if recieve_data == 1:
            #获取小车的经纬度lat_and_lon_car=[33,11,22,44,66,77,88,99]
            #这个是
            
            #lat_and_lon_car = GPS_SEND.GPS_datasend()
            
            lat_and_lon_car = [21,67,66,28,110,92,39,62]
            print(lat_and_lon_car)
            #for循环拼接成经度数组和纬度数组
            for i in range(4) :
                #获取纬度#[0xFF,0x06,0x01,33,11,22,44,0xAA]
                lat_car2[i+3] = lat_and_lon_car[i]
                #获取经度#[0xFF,0x06,0x02,66,77,88,99,0xAA]
                lon_car2[i+3] = lat_and_lon_car[i+4]
            sender.air_GPS(lat_car2)
            time.sleep(2)
            sender.air_GPS(lon_car2)
            recieve_data = 0
        if recieve_data == 9:
            #已经到达GPS目标点：
            print("reach goal")
            break
